﻿using Cms.Core.Application.IService.UserRoleInfo;
using Cms.Core.Application.Service.UserRoleInfo.Dto;
using Cms.Core.Data.Model;
using Cms.Core.Data.UnitOfWork;
using Cms.Core.Infrastructure.Common;
using Cms.Core.Infrastructure.Runtime.Session;
using Cms.Core.Infrastructure.Ui;
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Cms.Core.Application.Service.UserRoleInfo
{
    /// <summary>
    /// 用户角色接口
    /// </summary>
    public class UserRoleService: IUserRoleService
    {

        private readonly IRepository<SysUserRoleMap> _sysUserRoleMapRepository = null;

        private readonly ICmsSession _session = null;
        private readonly Guid? _userId = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sysUserRoleMapRepository"></param>
        /// <param name="session"></param>
        public UserRoleService(IRepository<SysUserRoleMap> sysUserRoleMapRepository, ICmsSession session)
        {
            this._sysUserRoleMapRepository = sysUserRoleMapRepository;

            this._session = session;
            this._userId = session.UserId;
        }


        /// <summary>
        /// 异步添加用户角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<OperationResult> AddUserRoleAsync(UserRoleDto input)
        {
          return await _sysUserRoleMapRepository.InsertAsync(input, async (dto) =>
            {

                CheckUserRoleIsNullOrEmpty(dto.UserId, dto.RoleId);

                await Task.CompletedTask;

            },async(dto,map)=> {

                map.CreateUserId = _session.UserId;
                await Task.CompletedTask;
                return map;
            });
        }

        /// <summary>
        /// 检查用户角色是否为空
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleId"></param>
        private void CheckUserRoleIsNullOrEmpty(Guid userId,Guid roleId)
        {
            if (userId==Guid.Empty||userId!=null)
            {
                throw new CustomException("用户名Id不能为空!!");
            }

            if (roleId == Guid.Empty || roleId != null)
            {
                throw new CustomException("角色不能为空!!");
            }
        }

  

       
    }
}
